package com.example.demo.framework.filters.tracer;

import com.example.demo.framework.utils.TraceUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Auther: miaoguoxin
 * @Date: 2020/3/20 09:25
 * @Description:
 */
@WebFilter(filterName = "traceFilter",urlPatterns = "/*")
@Slf4j
public class TraceFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            HttpServletRequest request=(HttpServletRequest)servletRequest;
            TraceInfo traceInfo = new TraceInfo();
            traceInfo.buildPrevious(request);
            traceInfo.buildCurrent(request);
            TraceUtils.set(traceInfo);
            filterChain.doFilter(servletRequest,servletResponse);
        }finally {
            log.info("移除traceInfo成功");
            TraceUtils.remove();
        }
    }
}
